package com.answerz.module_reportissues.viewmodel

import android.annotation.SuppressLint
import android.content.Context
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.annimon.stream.Collectors
import com.annimon.stream.Stream
import com.answerz.module_reportissues.BR
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.binding.command.BindingConsumer
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.*
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.vincent.videocompressor.VideoCompress
import com.luck.picture.lib.adapter.GridImageAdapter
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class ReportSubmitViewmodel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    var reportType = ObservableField("选择类型")
    var reportTypeId = ObservableField(-1)
    var reportLocation = ObservableField("选择位置")
    var reportContent = ObservableField("")
    var reportContentNum = ObservableField("")
    var canTouch = ObservableBoolean(true)
    var reportTypeData: SingleLiveEvent<List<OrderType>> = SingleLiveEvent()
    var submitSuccessEvent: SingleLiveEvent<Void> = SingleLiveEvent()
    var onClickType: BindingCommand<Void> = BindingCommand(BindingAction {
        getreportTypeData()
    })
    var reportLocationData: SingleLiveEvent<ArrayList<String>> = SingleLiveEvent()
    var onClickLocation: BindingCommand<Void> = BindingCommand(BindingAction {
        getreportLocationData()
    })
    var onClickSubmit: BindingCommand<Void> = BindingCommand(BindingAction {
        submitReport()
    })

    //    val startUploadEvent:SingleLiveEvent<Void> = SingleLiveEvent()
    val uploadImgEvent: SingleLiveEvent<UploadImgEventBean> = SingleLiveEvent()

    @SuppressLint("SimpleDateFormat")
    fun uploadImgAndVideo(fromIndex: Int, fileList: ArrayList<LocalMedia>, context: Context) {
//        Thread.sleep(3000)
        if (fromIndex < fileList.size) {
            fileList[fromIndex].imageState = GridImageAdapter.STATE_LOADING
            uploadImgEvent.postValue(UploadImgEventBean(fromIndex, true, fileList))
            if (TextUtils.isEmpty(fileList[fromIndex].remotePath)) {
                if (PictureMimeType.isHasVideo(fileList[fromIndex].mimeType)) {
                    if (TextUtils.isEmpty(fileList[fromIndex].compressPath)) {
                        var externalFilesDir =
                            context.getExternalFilesDir(Environment.DIRECTORY_MOVIES)
                        var customFile = File(externalFilesDir, "cache")
                        if (!customFile.exists()) {
                            customFile.mkdirs();
                        }
                        var destPath =
                            customFile.absolutePath + File.separator + "VID_" + SimpleDateFormat(
                                "yyyyMMdd_HHmmss"
                            ).format(
                                Date()
                            ) + ".mp4"
                        VideoCompress.compressVideoLow(
                            fileList[fromIndex].realPath,
                            destPath,
                            object :
                                VideoCompress.CompressListener {
                                override fun onStart() {
                                    Log.e(
                                        "ReportSubmitViewmodel",
                                        "--------------------------onStart"
                                    )
                                }

                                override fun onSuccess() {
                                    dismissLoading()
                                    fileList[fromIndex].compressPath = destPath
                                    fileList[fromIndex].imageState = GridImageAdapter.STATE_LOADING
                                    uploadImgEvent.postValue(
                                        UploadImgEventBean(
                                            fromIndex,
                                            true,
                                            fileList
                                        )
                                    )
                                    uploadImg(fromIndex, fileList, context)
                                    Log.e(
                                        "ReportSubmitViewmodel",
                                        "--------------------------onSuccess"
                                    )
                                }

                                override fun onFail() {
                                    fileList[fromIndex].imageState = GridImageAdapter.STATE_FAIL
                                    uploadImgEvent.postValue(
                                        UploadImgEventBean(
                                            fromIndex,
                                            true,
                                            fileList
                                        )
                                    )
                                    dismissLoading()
                                    uploadImgAndVideo(fromIndex + 1, fileList, context)
                                    Log.e(
                                        "ReportSubmitViewmodel",
                                        "--------------------------onFail"
                                    )
                                }

                                override fun onProgress(percent: Float) {
                                    Log.e(
                                        "ReportSubmitViewmodel",
                                        "--------------------------百分之" + percent
                                    )
                                }

                            })
                    } else {
                        uploadImg(fromIndex, fileList, context)
                    }
                } else {
                    uploadImg(fromIndex, fileList, context)
                }
            } else {
                fileList[fromIndex].imageState = GridImageAdapter.STATE_NORMAL
                uploadImgEvent.postValue(UploadImgEventBean(fromIndex, true, fileList))
                uploadImgAndVideo(fromIndex + 1, fileList, context)
            }
        }
    }

    fun uploadImg(fromIndex: Int, fileList: ArrayList<LocalMedia>, context: Context) {

        model.uploadHeadImg("gongdan", fileList[fromIndex].compressPath, "")
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe {}
            .subscribe(object : ApiSubscriberHelper<BaseBean<ImgRspBean>>() {
                override fun onResult(t: BaseBean<ImgRspBean>) {
                    dismissLoading()
                    if (t.code == 200) {
                        fileList[fromIndex].remotePath = t.data!!.url
                        fileList[fromIndex].imageState = GridImageAdapter.STATE_NORMAL
                        uploadImgEvent.postValue(UploadImgEventBean(fromIndex, true, fileList))
                    } else {
                        showErrorToast(t.msg)
                        fileList[fromIndex].imageState = GridImageAdapter.STATE_FAIL
                        uploadImgEvent.postValue(UploadImgEventBean(fromIndex, false, fileList))
                    }
                    uploadImgAndVideo(fromIndex + 1, fileList, context)
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                    fileList[fromIndex].imageState = GridImageAdapter.STATE_FAIL
                    uploadImgEvent.postValue(UploadImgEventBean(fromIndex, false, fileList))
                    uploadImgAndVideo(fromIndex + 1, fileList, context)
                }

            })
    }

    var localFiles = ObservableField<ArrayList<LocalMedia>>(ArrayList())
    private fun submitReport() {

        if (localFiles.get() != null && localFiles.get()!!.isNotEmpty()) {
            for (item in localFiles.get()!!) {
                if (item.imageState == GridImageAdapter.STATE_LOADING || item.imageState == GridImageAdapter.STATE_WAIT_LOADING) {
                    showNormalToast("请等待图片上传完成")
                    return
                }
            }
        }
        if (TextUtils.isEmpty(reportType.get().toString()) || TextUtils.equals(
                reportType.get().toString(), "选择类型"
            )
        ) {
            showNormalToast("请选择报修类型")
            return
        }
        //提交至后台
        if (TextUtils.isEmpty(
                reportLocation.get().toString()
            ) || TextUtils.equals(reportLocation.get().toString(), "选择位置")
        ) {
            showNormalToast("请选择报修位置")
            return
        }
        if (TextUtils.isEmpty(reportContent.get().toString())) {
            showNormalToast("请描述问题")
            return
        }
        var files = ArrayList<String>()
        if (localFiles.get() != null && localFiles.get()!!.isNotEmpty()) {
            for (item in localFiles.get()!!) {
                if (item.imageState != GridImageAdapter.STATE_FAIL && !TextUtils.isEmpty(item.remotePath)) {
                    files.add(item.remotePath)
                }
            }
        }
        var sub = SubmitReportRequestBean(
            model.getAreaId(), reportContent.get().toString(),
            files, reportLocation.get().toString(), "1", reportTypeId.get()!!.toInt()
        )
        model.submitReport(sub).compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe {
                canTouch.set(false)
                showLoading()
            }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any>>() {
                override fun onResult(t: BaseBean<Any>) {
                    dismissLoading()
                    canTouch.set(true)
                    if (t.code == 200) {
                        showSuccessToast("提交成功！")
                        submitSuccessEvent.call()
                    } else {
                        showErrorToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    canTouch.set(true)
                    showErrorToast(msg)
                }

            })
    }

    private fun getreportLocationData() {
        //请求接口获取报事位置列表数据
        model.getUserRooms(model.getLoginPhone().toString(), model.getAreaId())
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(
                object : ApiSubscriberHelper<BaseBean<List<RoomBean>>>() {
                    override fun onResult(t: BaseBean<List<RoomBean>>) {
                        dismissLoading()
                        if (t.code == 200) {
                            var locations = ArrayList<String>()
                            for (item in t.data!!) {
                                locations.add(item.houseCode)
                            }
                            reportLocationData.postValue(locations)
                            t.data?.let {
                                var rooms = Stream.of(it).map { e -> e.houseId + e.houseCode }
                                    .collect(Collectors.toList())
                                model.saveRoomIdAndCode(GsonUtils.toJson(rooms))
                            }

                        } else {
                            reportLocationData.postValue(null)
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        reportLocationData.postValue(null)
                        showErrorToast(msg)
                    }

                }
            )
    }

    private fun getreportTypeData() {
        //请求接口获取报事类型列表数据
        model.apply {
            getOrderType(5, getAreaId())
                .compose(RxThreadHelper.rxSchedulerHelper(this@ReportSubmitViewmodel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<List<OrderType>>>() {
                    override fun onResult(t: BaseBean<List<OrderType>>) {
                        dismissLoading()
                        if (t.code == 200) {
                            reportTypeData.postValue(t.data)
                        } else {
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }

                })
        }

    }

    public fun reportContentLength(content: String): String {
        return content.length.toString() + "/150"
    }
}